<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\AdminUser\Logic;

use Hyperf\Di\Annotation\Inject;
use MoChat\Plugin\AdminUser\Contract\AdminUserContract;
use MoChat\Plugin\AdminUser\Contract\AdminUserLevelContract;

/**
 * 子账户管理-列表.
 *
 * Class IndexLogic
 */
class IndexLogic
{
    /**
     * @Inject
     * @var AdminUserContract
     */
    protected $adminUserService;

    /**
     * @Inject
     * @var AdminUserLevelContract
     */
    protected $adminUserLevelService;

    /**
     * @param array $params 请求参数
     * @param array $adminUser 当前登录用户信息
     * @return array 响应数组
     */
    public function handle(array $params, array $adminUser): array
    {
        # # 组织查询条件
        $where = [];
        $options = [
            'page' => $params['page'],
            'perPage' => $params['perPage'],
            'orderByRaw' => 'id desc',
        ];
        $parentId = 0;
        if ($adminUser['isRoot'] === 0) {
            $where['parent_id'] = $adminUser['id'];
            $parentId = $adminUser['id'];
        }
        # # 租户名称/手机号
        if (! empty($params['phone'])) {
            $where[] = ["((`name` LIKE '%{$params['phone']}%') OR (`phone` LIKE '%{$params['phone']}%'))"];
        }
        if (! empty($params['startTime'])) {
            $where[] = ['created_at', '>=', $params['startTime']];
            $where[] = ['created_at', '<=', $params['endTime']];
        }
        if (! empty($params['level'])) {
            $where['level'] = $params['level'];
        }

        # # 查询数据
        $res['data'] = $this->adminUserService->getAdminUserListBySearch((int) $parentId, $params['status'], $params['phone'], $params['startTime'], $params['endTime'], (int) $params['level']);

        # # 组织响应数据
        $data = [
            'page' => [
                'perPage' => $params['perPage'],
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];

        if (empty($res['data'])) {
            return $data;
        }
//        ## 处理分页数据
//        $data['page']['total'] = $res['total'];
//        $data['page']['totalPage'] = $res['last_page'];
        # # 处理数据
        foreach ($res['data'] as &$v) {
            $level = $this->adminUserLevelService->getAdminUserLevelById($v['level'], ['name']);
            $v['levelName'] = $level ? $level['name'] : '';
            unset($v['password'], $v['updatedAt'], $v['deletedAt']);
        }
        $data['list'] = $res['data'];

        return $data;
    }
}
